<template>
    <el-dialog :title="dialogProps.title" :visible.sync="dialogProps.visible" width='650px'  :fullscreen = 'Global.currentDevice'  align='center'>
        <el-tabs  >
            <el-tab-pane label="用户信息" name="first"></el-tab-pane>
        </el-tabs>
        <el-image :src="src" class='bg-ccc'></el-image>
        <el-form  :label-width="formLabelWidth" :label-position='Global.dialog_label_Position' class='mt12' align='left' :model="form" ref='form' :rules='rules' size='medium'>
            <el-col :xs='24' :lg='12'>
                <el-form-item label="姓名："  prop='name'>
                    <el-input v-model.trim="form.name" placeholder="请输入姓名" ></el-input>
                </el-form-item>
                <el-form-item label="性别：">
                    <el-radio-group v-model.trim="form.gender" >
                        <el-radio label="1">男</el-radio>
                        <el-radio label="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="登录名："  prop='loginName'>
                    <el-input v-model.trim="form.loginName" placeholder="请输入登录名" ></el-input>
                </el-form-item>

                <el-form-item label="密码："  :prop='isEdit==false? "loginPassword" : "" ' >
                    <!-- 新增 -->
                    <el-input  v-if='isEdit==false'  v-model.trim="form.loginPassword" placeholder="请输入密码"  type='password'  :show-password='true'></el-input>
                    <!-- 编辑 -->
                    <span  v-else>
                        <!-- 编辑查看 -->
                        <span  v-if='passModify==false'>
                            ******
                            <el-button  class='export-icon ml10'  size="small" round  @click="passModify = true">修改密码</el-button>
                        </span>
                        <!-- 编辑修改 -->
                        <span v-else>
                            <el-input v-model.trim="form.loginPassword" placeholder="请输入密码" v-focus type='password' style='width:89%;'  :show-password='true'></el-input>
                            <span><i class="el-icon-circle-close ft18 color-red cursor" title='取消' @click="passModify = false" ></i></span>
                        </span>
                    </span>
                </el-form-item>
                <el-form-item label="确认密码："   :prop='isEdit==false? "repassword":"" '  v-if='isEdit==false'>
                    <el-input v-model.trim="form.repassword" placeholder="请确认密码"  type='password'  :show-password='true'></el-input>
                </el-form-item>

                <el-form-item label="手机号："  prop='mobile'>
                    <el-input v-model.trim="form.mobile" placeholder="请输入手机号"  ></el-input>
                </el-form-item>
            </el-col>
            <el-col :xs='24' :lg='12' class='adduserlist'>
                <el-form-item label="职位：">
                    <el-radio-group v-model.trim="form.position">
                        <el-radio label="1">负责人</el-radio>
                        <el-radio label="2">普通员工</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="角色：" >
                    <el-select v-model.trim="roles" multiple placeholder="选择角色"  class='w-100' >
                        <el-option
                          v-for="(item,index) in roleList"
                          :key="index"
                          :label="item.name"
                          :value="item.code">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="标签：">
                    <el-select v-model.trim="tags" multiple placeholder="选择标签"  class='w-100' >
                        <el-option
                          v-for="item in labelList"
                          :key="item.code"
                          :label="item.tagName"
                          :value="item.code">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="部门：">
                    {{currentApartNode}}
                    <el-button  class='export-icon ml10'  size="small" round  @click="change()">修改</el-button>
                </el-form-item>
                <el-form-item label="工号："  prop='num'>
                    <el-input v-model.trim="form.num" placeholder="请输入工号"   ></el-input>
                </el-form-item>
                <el-form-item label="邮箱："  prop='mail'>
                    <el-input v-model.trim="form.mail" placeholder="请输入邮箱"   ></el-input>
                </el-form-item>
            </el-col> 
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="close()">取 消</el-button>
            <el-button type="primary" @click.native.prevent="submit('form')"  :loading='displayLoading' >确 定</el-button>
        </div>
        <chooseApart ref="choose_apart" :parentlist='parentgroup' v-on:save="changeResult(arguments)"></chooseApart>
    </el-dialog>
</template>

<script charset="utf-8" type="text/javascript">
/*interface*/
import { saveUser , getUserDetail ,modifyUser}  from  '@/api/user/index'
/*components*/ 
//                新增/编辑
import  chooseApart  from '@/components/userlist/chooseApart'
export default {
  name: 'EditUser',
    props:{
    parentgroup: {
        type: Array,
        default:function(){
              return [];
        }
    },
    roleList : {
        type: Array,
        default:function(){
              return [];
        }
    },
    labelList : {
        type: Array,
        default:function(){
              return [];
        }
    }   
  },
  data() {
      let validatePass2 = (rule, value, callback) => {
          if (value === '') {
              callback(new Error('请再次输入密码'));
          } else if (value !== this.form.loginPassword && value !== '') {
              callback(new Error('两次输入密码不一致!'));
          } else {
              return callback();
          }
      };
      return {
          /*static*/
          //dialogo基本信息  显示隐藏状态  title 
          dialogProps: {
            visible: false,
            action: '',
            title: '用户详情'
          },
          formLabelWidth:'100px',
          /*submit按钮等待加载状态*/
          displayLoading: false,
          /*用户头像背景图，默认*/
          src:'static/img/user/icon-default-user.png',
          /*新增项目默认上级部门为根部门*/
          currentApartNode:'根部门',
          /*active*/
          /*表单状态*/
          isEdit:false,
          passModify:false,
          form:{
            name:"",
            gender:"1",
            loginName:"",
            loginPassword:"",
            mobile:"",
            position:"1",
            roles:[],
            tags:'',//角色code
            officeCode:"root",/*新增用户默认上级部门为根部门*/
            num:"",
            mail:"",
          },
          roles:[],
          tags:[],
          repassword:'',
          rules:{
            name:[
              {required : true, message : "请输入姓名"}
            ],

            loginName:[
              {required : true, message : "请输入登录名"}
            ],
            loginPassword:[
              {required : true, message : "请输入密码"}
            ],
            repassword:[
              { validator: validatePass2, trigger: 'blur' }
            ],
            mobile:[
                { validator: this.checkTel ,trigger: 'blur'}
            ],
            mail:[
                { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
            ]
          },
      }
  },
  created(){
    
  },
  methods: {
    //变更上级部门
    change(){
        this.$refs.choose_apart.$emit('openChoose',this.form.officeCode)
    },
    //变更上级部门结果
    changeResult(arg){
      [this.form.officeCode,this.currentApartNode]=[arg[0],arg[1]]
    },
    submit(formName) {
      let that = this
      // console.log(11)
      //先验证表达
      this.$refs[formName].validate(valid => {
          //通过验证后
          // console.log(valid)
          if (valid) {
                  this.displayLoading = true/*submit按钮等待加载状态*/
                  this.form.roles = []
                  this.form.tags=''
                  this.roles.forEach((item)=>{
                      this.form.roles.push({code:item})
                  })
                  this.tags.forEach((item)=>{
                      this.form.tags+=item+','
                  })

                  if(this.form.roles.length == 0){
                      that.displayLoading = false/*submit按钮等待加载状态*/
                      return  this.$message({type:'error',message:'请至少选择一个角色'})
                  }
                  if(this.isEdit == false){
                      saveUser(this.form).then(res=>{
                          if(res.data.flag == true){
                              this.$message({type:'success',message:res.data.msg})
                              this.$emit('save-finished')
                              this.dialogProps.visible=false
                          }
                          that.displayLoading = false/*submit按钮等待加载状态*/
                      })
                      .catch(error=>{
                          that.displayLoading = false/*submit按钮等待加载状态*/
                      })
                  }
                  else{
                      modifyUser(this.form).then(res=>{
                          if(res.data.flag == true){
                            this.$message({type:'success',message:res.data.msg})
                            this.$emit('save-finished')
                            this.dialogProps.visible=false 
                          }
                          that.displayLoading = false/*submit按钮等待加载状态*/
                      })
                      .catch(error=>{
                          that.displayLoading = false/*submit按钮等待加载状态*/
                      })
                  }
                  
          } 
          else {
            return false;
          }
      });
    },
    close(){
      this.passModify=false
      // this.resetForm('form')
      
      this.dialogProps.visible = false
      this.form={
            name:"",
            gender:"1",
            loginName:"",
            loginPassword:"",
            mobile:"",
            position:"1",
            roles:[],
            tags:'',
            officeCode:"root",
            num:"",
            mail:"",
        };
        this.roles= []
        this.tags = []
        this.repassword =''
        this.currentApartNode = '根部门'
        this.$refs.form.clearValidate()
    }
  },
  mounted: function() {
      this.$nextTick(() => {
          this.$on('openAddDialog', function() {
              this.dialogProps.visible = true
              this.isEdit = false
              // this.resetForm('form')
              this.form={
                  name:"",
                  gender:"1",
                  loginName:"",
                  loginPassword:"",
                  mobile:"",
                  position:"1",
                  roles:[],
                  tags:'',
                  officeCode:"root",
                  num:"",
                  mail:"",
              };
              this.roles= []
              this.tags = []
              this.repassword =''
              this.currentApartNode = '根部门'
              // this.$refs.form.clearValidate()
              this.$nextTick(() => {
                  this.$refs.form.clearValidate()
              })
          })
          this.$on('openEditDialog' , function(data) {
              this.isEdit = true
              this.passModify=false
              // console.log(data)  不能用data 编辑取消时也会绑定值
              getUserDetail(data.code).then(res=>{
                  /*显示dialog在请求之后，加载dialog内容也可以等待*/
                  this.dialogProps.visible = true
                  this.form=res.data.data
                  //角色回填
                  let rolearr = res.data.data.roles
                  this.roles = []
                  rolearr.forEach((item)=>{
                    this.roles.push(item.code)
                  })
                  //标签回填
                  this.tags=[]
                  
                  if(this.form.tags.length !=0 ){
                      this.tags=this.form.tags.slice(0,-1).split(',')
                      // console.log(this.tags)  注意回填写在请求里面！！！！！
                  }
                  //将密码设置为空
                  this.form.loginPassword = ''
                  // this.resetForm('form')
              })
              //跟部门,从上一级过来，不需要重
              this.currentApartNode = data.officeName
              // this.form = data
              this.$nextTick(() => {
                  this.clearValidateForm('form')
              })
          })
      })
  },
  updated(){
    
  },
  components:{
      chooseApart
  }
}
</script>

<style  scoped>

</style>


